﻿using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace 深入浅出WPF_BookDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Student stu;

        public MainWindow()
        {
            InitializeComponent();
            SetCalcuBinding();
            //SetRelativeSource();
            SetValidation();
            stu = new Student();

            Binding binding = new Binding();

            binding.Source = stu;

            binding.Path = new PropertyPath("Name");

            //BindingOperations.SetBinding(this.txt_1, TextBox.TextProperty, binding);

            //this.txt_1.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = stu });

            //this.textBox1.SetBinding(TextBox.TextProperty, new Binding("Value") { ElementName = "slider1", UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });

            List<Student> students = new List<Student>() {
                new Student(){Id = 0,Name = "Tim0",Age = 29},
                new Student(){Id = 1,Name = "Tim1",Age = 28},
                new Student(){Id = 2,Name = "Tim2",Age = 27},
                new Student(){Id = 3,Name = "Tim3",Age = 26},
                new Student(){Id = 4,Name = "Tim4",Age = 25},
                new Student(){Id = 5,Name = "Tim5",Age = 24}
            };

            this.listBoxStudents.ItemsSource = students;
            //设置ItemTemplate
            //this.listBoxStudents.DisplayMemberPath = "Name";
            Binding binding1 = new Binding("SelectedItem.Id") { Source = this.listBoxStudents };
            this.textBoxId.SetBinding(TextBox.TextProperty, binding1);

        }

        private void SetValidation()
        {
            Binding binding = new Binding("Value") { Source = this.sliderValida };
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            RangeValidationRule rule = new RangeValidationRule();
            rule.ValidatesOnTargetUpdated = true;
            binding.ValidationRules.Add(rule);
            binding.NotifyOnValidationError = true;
            this.textBoxValida.SetBinding(TextBox.TextProperty, binding);

            this.textBoxValida.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(this.ValidationError));
        }

        void ValidationError(object? sender, RoutedEventArgs e)
        {
            if (Validation.GetErrors(this.textBoxValida).Count > 0)
            {
                this.textBoxValida.ToolTip = Validation.GetErrors(this.textBoxValida)[0].ErrorContent.ToString();
            }
        }


        //也可以用Xaml代码
        //private void SetRelativeSource()
        //{
        //    RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor);
        //    rs.AncestorLevel = 2;
        //    rs.AncestorType = typeof(Grid);
        //    Binding binding = new Binding("Name") { RelativeSource = rs };
        //    this.textbox0001.SetBinding(TextBox.TextProperty, binding);
        //}

        private void btn_1_Click(object sender, RoutedEventArgs e)
        {
            stu.Name += ",Name";
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(btn.DataContext.ToString());
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(textInner01.DataContext.ToString());
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"E:\Software\Code\Study\深入浅出WPF BookDemo\Data\RawData.xml");

            XmlDataProvider xdp = new XmlDataProvider();
            xdp.Document = doc;

            xdp.XPath = @"StudentList/Student";
            this.listViewStudents.DataContext = xdp;
            this.listViewStudents.SetBinding(ListView.ItemsSourceProperty, new Binding());
        }

        private void SetCalcuBinding()
        {
            ObjectDataProvider odp = new ObjectDataProvider();
            odp.ObjectInstance = new Calculator();
            odp.MethodName = "Add";
            odp.MethodParameters.Add("0");
            odp.MethodParameters.Add("0");

            Binding bindingToArg1 = new Binding("MethodParameters[0]")
            {
                Source = odp,
                BindsDirectlyToSource = true,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            };

            Binding bindingToArg2 = new Binding("MethodParameters[1]")
            {
                Source = odp,
                BindsDirectlyToSource = true,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            };

            //bindingToResult绑定了textBoxResult的TextProperty到ObjectDataProvider.Object。
            //ObjectDataProvider.Object是一个依赖属性，
            //其值反映了ObjectDataProvider最近一次调用指定方法的结果。
            Binding bindingToResult = new Binding(".")
            {
                Source = odp
            };

            this.textBoxArg1.SetBinding(TextBox.TextProperty, bindingToArg1);
            this.textBoxArg2.SetBinding(TextBox.TextProperty, bindingToArg2);
            this.textBoxArg3.SetBinding(TextBox.TextProperty, bindingToResult);
        }


    }



    public class Student : INotifyPropertyChanged
    {
        private int _id;
        public int Id
        {
            get { return _id; }
            set
            {
                _id = value;
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Id"));
            }
        }

        private string _name = "Jack";

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
            }
        }

        private int _age;

        public int Age
        {
            get { return _age; }
            set
            {
                _age = value;
                this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Age"));
            }
        }


        public Student()
        {

        }

        public event PropertyChangedEventHandler? PropertyChanged;
    }

    class Calculator
    {
        public string Add(string arg1, string arg2)
        {
            double x = 0; double y = 0; double z = 0;
            if (double.TryParse(arg1, out x) && double.TryParse(arg2, out y))
            {
                z = x + y;
                return z.ToString();
            }
            return "Input Error";
        }
    }

    public class RangeValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            double d = 0;
            if (double.TryParse(value.ToString(), out d))
            {
                if (d >= 0 && d <= 100)
                {
                    return new ValidationResult(true, null);
                }
            }
            return new ValidationResult(false, "Validation Failed");
        }
    }



}